import React, { useState } from 'react';
import { Text, TextInput, View } from "react-native";
import tw from "twrnc";
import Icon from 'react-native-vector-icons/AntDesign';
import { router } from 'expo-router';
import CountryFlag from 'react-native-country-flag';
import { Modal, } from 'react-native-paper';
import NavBar from "@/components/NavBar";
import DateTimePicker from 'react-native-dates-picker';
import dayjs from 'dayjs'
import { useDispatch, useSelector } from 'react-redux';
import { setDate, setNickname } from '@/store/modules/InfoSlice';
import * as SecureStore from 'expo-secure-store';
import { NavigationProp, useNavigation } from '@react-navigation/native';

type RootStackParamList = {
    'avatar-setting': { id: string };
    // 其他路由的参数类型
};

export default function PerfectInfo() {
    const navigation = useNavigation<NavigationProp<RootStackParamList>>();
    const dispatch = useDispatch();
    const { gender, country, selectedDate, nickname, language } = useSelector((state: any) => state.InfoSlice);

    const handleNicknameChange = (text) => {
        dispatch(setNickname(text));
    };

    /* 日期 */
    const containerStyle = {
        backgroundColor: 'white',
        padding: 10,
        height: 400,
        margin: 50,
        borderRadius: 10,
    };
    const [dateVisible, setDateVisible] = useState(false);
    const [date, setDateState] = useState(dayjs(selectedDate));

    const showdateModal = () => {
        setDateVisible(true);
    };

    const hidedateModal = () => {
        setDateVisible(false);
    };

    const handleConfirm = () => {
        dispatch(setDate(dayjs(date).format('YYYY-MM-DD')));
        setDateVisible(false);
    }

    const handleCancel = () => {
        setDateVisible(false);
    }

    // 保存数据
    const saveData = async (key, value) => {
        await SecureStore.setItemAsync(key, value);
    };


    // 生成四位随机数
    const generateRandomNumber = () => {
        return Math.floor(Math.random() * 10000).toString().padStart(4, '0');
    };

    // 获取当前时间戳
    const getCurrentTimestamp = () => {
        return Date.now();
    };

    // 生成 id
    const generateUserId = () => {
        const randomNumber = generateRandomNumber();
        const timestamp = getCurrentTimestamp();
        return randomNumber + timestamp;
    };


    const handleNext = async () => {
        let userListStr = await SecureStore.getItemAsync('userList')
        let userList = userListStr ? JSON.parse(userListStr) : [];
        let phoneNumber = await SecureStore.getItemAsync('phoneNumber')
        let user = userList.find(item => item.phoneNumber === phoneNumber)

        if (user) {
            user.id = generateUserId();
            user.nickname = nickname;
            user.gender = gender;
            user.country = country;
            user.selectedDate = selectedDate;
            user.language = language;
            user.avatar = '';
            userListStr = JSON.stringify(userList);
            await SecureStore.setItemAsync('userList', userListStr);
            navigation.navigate('avatar-setting', { id: user.id });
        }
    }


    return (
        <View style={tw`flex-1`}>
            <NavBar title="信息完善" rightElement={true} />
            <View style={tw`flex-1 p-4`}>
                <View style={tw`flex-row items-center justify-between border-2 border-gray-300 rounded-full my-1.5 p-2`}>
                    <View style={tw`flex-row items-center`}>
                        <Text style={tw`text-red-500`}>*</Text>
                        <Text>国籍/地区</Text>
                    </View>
                    <View style={tw`flex-row items-center`}>
                        <CountryFlag isoCode={`${country.isoCode}`} size={30} style={tw`rounded-full h-5 w-5 mx-3px`} />
                        <View style={tw`mx-1`}><Text>{country.name}</Text></View>
                        <Icon name="right" size={10} color="#A7ABAA"
                            style={tw`border rounded-full border-slate-300 p-1`}
                            onPress={() => { router.push('/(auth)/country-area') }}
                        />
                    </View>
                </View>
                <View style={tw`flex-row items-center justify-between border-2 border-gray-300 rounded-full my-1.5 p-2`}>
                    <View style={tw`flex-row items-center`}>
                        <Text style={tw`text-red-500`}>*</Text>
                        <Text>我的语言</Text>
                    </View>
                    <View style={tw`flex-row items-center`}>
                        <View style={tw`mx-1`}><Text>{language}</Text></View>
                        <Icon name="right" size={10} color="#A7ABAA"
                            style={tw`border rounded-full border-slate-300 p-1`}
                            onPress={() => { router.push('/(auth)/language') }}
                        />
                    </View>
                </View>
                <View style={tw`flex-row items-center justify-between border-2 border-gray-300 rounded-full my-1.5 p-2`}>
                    <View style={tw`flex-row items-center`}>
                        <Text style={tw`text-red-500`}>*</Text>
                        <Text>昵称</Text>
                    </View>
                    <View style={tw`flex-row items-center`}>

                        <View style={tw`mx-1`}>
                            <TextInput
                                style={tw`text-right`}
                                placeholder="请填写昵称"
                                placeholderTextColor="#999999"
                                value={nickname}
                                onChangeText={handleNicknameChange}
                            /></View>
                        <Icon name="right" size={10} color="#A7ABAA" style={tw`border rounded-full border-slate-300 p-1`} />
                    </View>
                </View>
                <View style={tw`flex-row items-center justify-between border-2 border-gray-300 rounded-full my-1.5 p-2`}>
                    <View style={tw`flex-row items-center`}>
                        <Text style={tw`text-red-500`}>*</Text>
                        <Text>出生日期</Text>
                    </View>
                    <View style={tw`flex-row items-center`}>

                        <View style={tw`mx-1`}>
                            {selectedDate ? <Text>{selectedDate}</Text> : <Text style={tw`text-gray-400`}>请选择出生日期</Text>}
                        </View>
                        <Icon name="right" size={10} color="#A7ABAA" style={tw`border rounded-full border-slate-300 p-1`} onPress={showdateModal} />
                    </View>
                </View>
                <View style={tw`flex-row items-center justify-between border-2 border-gray-300 rounded-full my-1.5 p-2`}>
                    <View style={tw`flex-row items-center`}>
                        <Text style={tw`text-red-500`}>*</Text>
                        <Text>性别</Text>
                    </View>
                    <View style={tw`flex-row items-center`}>
                        <View style={tw`mx-1`}>
                            {gender ? <Text>{gender}</Text> : <Text style={tw`text-gray-400`}>请选择性别</Text>}
                        </View>
                        <Icon name="right" size={10} color="#A7ABAA"
                            style={tw`border rounded-full border-slate-300 p-1`}
                            onPress={() => { router.push('/(auth)/select-gender') }} />
                    </View>
                </View>

                <View style={tw`flex-row items-center justify-center`}>
                    <View style={tw`w-25 border-2 border-gray-300 rounded-full my-1.5 p-2`}>
                        <Text style={tw`text-center`} onPress={handleNext}>下一步</Text>
                    </View>
                </View>


                <View style={tw`flex-row items-center justify-center absolute bottom-2 left-0 right-0`}>
                    <Text style={tw`text-gray-400`}>国籍/地区和性别提交后不可修改，请使用真实资料</Text>
                </View>
            </View>

            {/* 日期Modal */}
            <Modal visible={dateVisible} onDismiss={hidedateModal} contentContainerStyle={containerStyle} >
                <View style={tw`flex-1 justify-center py-2`}>
                    <DateTimePicker
                        mode="single"
                        date={date}
                        onChange={(params) => setDateState(dayjs(params.date))}
                        selectedItemColor={'#26EBD7'}
                    />
                </View>
                <View style={tw`flex-row items-center justify-center`}>
                    <View style={tw`bg-teal-300 flex items-center justify-center rounded-md w-24 h-10 mx-8px`}><Text style={tw`text-center`} onPress={handleCancel}>取消</Text></View>
                    <View style={tw`bg-teal-300 flex items-center justify-center rounded-md w-24 h-10 mx-8px`}><Text style={tw`text-center`} onPress={handleConfirm}>确认</Text></View>
                </View>
            </Modal>
        </View>
    )
}